<template>
  <div>
    <h1 class="my-4 px-4 text-4xl font-semibold">标签管理:</h1>
    <div class="my-4">新建标签:</div>
    <div>
      <ZInput v-model="name" @keydown.enter="onNewTag" :debounce-ms="0" />
    </div>
    <div>
      <div class="my-4">预定义 Tags:</div>
      <div class="flex flex-wrap gap-4 bg-base-200 p-4">
        <div
          class="rounded-md bg-primary p-4 text-primary-content"
          v-for="tag in tagsStore.predefineTags"
          :key="tag.id"
        >
          {{ tag.name }}
        </div>
      </div>
    </div>
    <div v-if="tagsStore.customTags.length > 0">
      <div class="my-4">自定义 Tags:</div>
      <div class="flex flex-wrap gap-4 bg-base-200 p-4">
        <div
          v-for="tag in customTags"
          :key="tag.id"
          class="flex items-center justify-between rounded-md bg-secondary pr-2 text-secondary-content"
        >
          <ZTextInput
            :contenteditable="isModify"
            class="h-full w-full cursor-pointer text-ellipsis border-none bg-transparent p-4 pr-8 focus:outline-none"
            v-model="tag.name"
            @click="isModify = true"
            @keydown.enter="onChangeTag(tag)"
            @blur="
              tag.name = tagsStore.customTags.filter(
                (item) => item.id === tag.id,
              )[0].name
            "
          />
          <span
            class="icon-[uil--multiply] h-6 w-6 text-secondary-content/50 hover:cursor-pointer hover:text-secondary-content"
            @click="deleteTag(tag.id)"
          ></span>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { useTagsStore } from "@/stores/tags";
import { Tag } from "@/stores/types";
import { useApiFetch, ApiResponse } from "@/composables/useApiFetch";

const tagsStore = useTagsStore();
tagsStore.load();
let customTags: Tag[] = tagsStore.customTags;

const name = ref("");
// 是否是可编辑模式
const isModify = ref(false);

// 新建标签
const onNewTag = async () => {
  const newTag = (await tagsStore.newTag(name.value)).value?.object;
  name.value = "";
  // 更新 customTags
  customTags.push(newTag as Tag);
};

// 修改标签
const onChangeTag = async (tag: Tag) => {
  const { id, name } = tag;
  const { data } = await useApiFetch(`/user/tags/${id}`)
    .put({ name })
    .json<ApiResponse<Tag>>();
  if (data.value?.success) {
    // 更新 customTags
    tagsStore.load();
  } else {
    // 如果失败，回到原来的值
    customTags = tagsStore.customTags;
    isModify.value = false;
  }
};

// 删除标签
const deleteTag = async (id: number) => {
  const { data } = await useApiFetch(`/user/tags/${id}`).delete().json();
  if (data.value?.success) {
    // 更新 customTags: 通过 filter 过滤掉删除的标签
    customTags = customTags.filter((tag) => tag.id !== id);
    // 更新 customTags
    tagsStore.load();
  }
};
</script>
